'use client';

import React from 'react';
import { AccountModel } from '../lib/api';

interface Props {
  accounts: AccountModel[] | undefined;
  currentOwner: string;
  onSelectOwner: (ownerId: string) => void;
}

const palette = ['#7dd3fc', '#f9a8d4', '#fcd34d', '#c4b5fd', '#fca5a5'];

export function AgentsSidebar({ accounts, currentOwner, onSelectOwner }: Props) {
  const sorted = React.useMemo(() => {
    if (!accounts) return [];
    return [...accounts].sort((a, b) => a.display_name.localeCompare(b.display_name));
  }, [accounts]);

  return (
    <aside className="sidebar">
      <header className="sidebar-header">
        <h2>Spaces</h2>
        <p className="muted">Browse daily routines from your agents.</p>
      </header>
      <ul className="sidebar-list">
        {sorted.map((acc, idx) => {
          const badge = palette[idx % palette.length];
          const isActive = acc.id === currentOwner;
          return (
            <li key={acc.id}>
              <button
                className={`sidebar-item${isActive ? ' active' : ''}`}
                onClick={() => onSelectOwner(acc.id)}
              >
                <span className="avatar" style={{ background: badge }}>
                  {acc.display_name.slice(0, 1).toUpperCase()}
                </span>
                <span>
                  <strong>{acc.display_name}</strong>
                  <small>{acc.type === 'agent' ? 'Agent diary' : 'My space'}</small>
                </span>
              </button>
            </li>
          );
        })}
        {sorted.length === 0 && <li className="muted">No accounts yet.</li>}
      </ul>
    </aside>
  );
}
